import axios from 'axios'
import qs from 'qs'
import * as actions from '../actionTypes/'

import config from './config.js'
import store from '../store/'

const instance = axios.create({
    baseURL: config.API,
    withCredentials: true,
    timeout: 50000,
    headers: {
        'content-type': 'application/x-www-form-urlencoded',
    },
})

instance.interceptors.request.use(
    config => {
        return config
    },
    error => Promise.reject(error)
)

instance.interceptors.response.use(
    response => {
        if (response.config.url.indexOf('getCurrentUser') === -1) {
            if (!response.data.success) {
                store.dispatch({
                    type: actions.SHOW_TOAST,
                    payload: response.data.message,
                })
            }
        }
        return response.data
    },
    error => {
        handleErrorStatus(error.response)
        return Promise.reject(error.response)
    }
)

const handleErrorStatus = ({ status }) => {
    const errorTxt = config.errorTypes[status]
    if (errorTxt) {
        store.dispatch({
            type: actions.SHOW_TOAST,
            payload: errorTxt,
        })
    }
}

let requests =  (url = '', data = {}, method = 'get', origin = false) => {
    const postData = qs.stringify(data, { arrayFormat: 'repeat' })
    const options = method.toLowerCase() === 'get' ? { params: data } : postData

    return instance[method](url, options)
        .then(res => {
            // origin = true 则返回data外层data
            return origin ? res : res.data
        })
        .catch(err => {
            console.log(err)
            return false
        })
}

export default requests;

// WEBPACK FOOTER //
// ./src/utils/request.js